package com.dfhc.pub.service;


import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.common.vo.RmCommonVo;
import org.springframework.stereotype.Service;

import com.dfhc.ISystemConstant;
import com.dfhc.util.CommentFileFilter;
import com.dfhc.util.FileOperateHelper;
import com.dfhc.util.StringHelper;

/**
 * 
 * @author ASUS
 * 从jsp页面提取链接
 */
@Service
public class PickMenuLinkInPageService {
	private Pattern firstwp;
	private String insertSql;
	private String updateSeqSeql;
	
	private String insertAuthResourceSql;
	
	private ArrayList<String> menuLinkList;
    private Map<String,String> exitsMenuMap;
    /**
     * 初始化
     */
    public void init() {
    	String firstRegex =  RmGlobalReference.get(ISystemConstant.REGULAR_EX, "01");
		firstwp = Pattern.compile(firstRegex,Pattern.DOTALL);
		menuLinkList = new ArrayList<String>();
	}
    public void clearMenuList(){
    	if(menuLinkList!=null){
    		menuLinkList.clear();
    	}
    }
	/**
	 * 提取菜单
	 * @param path 提取目录
	 * @param menuCodeList 菜单码列表
	 * @param sqlFile 生成的sql文件名
	 * @throws Exception 
	 */
	public void doPickMenu(String path,List<String> menuCodeList,String sqlFile) throws Exception{
		init();
		initMenuList();
		FilenameFilter fileFilter = new CommentFileFilter(".*.jsp");
		List<String> files = FileOperateHelper.searchFile(path, fileFilter);
		
		insertSql="INSERT INTO RM_FUNCTION_NODE (ID, NODE_TYPE, FUNCTION_PROPERTY, NAME, ENABLE_STATUS, TOTAL_CODE, ORDER_CODE, FUNCNODE_AUTHORIZE_TYPE, DESCRIPTION, DATA_VALUE, PATTERN_VALUE, IS_LEAF, ICON, HELP_NAME, USABLE_STATUS, MODIFY_DATE, MODIFY_IP, MODIFY_USER_ID)"+
				  "VALUES ("+
				  "(select substr(SEQUENCE_RULE,1,4)||to_char(sysdate,'YYYYMMDD')||to_char(CURRENT_VALUE+1,'FM0000000') from base_impulse_sender where sequence_name='RM_FUNCTION_NODE'),"+
				  "'2', '%s', '%s', '1', '%s%03d', null, '1', null, '%s', null, '1', null, null, '1', sysdate, '192.168.1.200', 1000201100000000001);";
		//RM_FUNCTION_NODE
        updateSeqSeql="update base_impulse_sender set current_value=current_value+1,current_fmt_value=substr(SEQUENCE_RULE,1,4)||to_char(sysdate,'YYYYMMDD')||to_char(CURRENT_VALUE+1,'FM0000000'),"+
      			  "update_date = sysdate  where sequence_name='%s' ;";
        insertAuthResourceSql="INSERT INTO RM_AUTHORIZE_RESOURCE(id,name,modify_date,authorize_id,old_resource_id,total_code,default_access,"+
        					  " default_is_affix_data,default_is_recursive,default_access_type) "+
        					  "	VALUES((select substr(SEQUENCE_RULE,1,4)||to_char(sysdate,'YYYYMMDD')||to_char(CURRENT_VALUE+1,'FM0000000') from base_impulse_sender where sequence_name='RM_FUNCTION_NODE'),'%s',sysdate,'1000202400000000001','%s%03d','%s%03d',0,0,0,1);";
         
        for(String fileName:files){
			pickLinkFromFile(fileName,menuCodeList);
		}
      //循环拼接sql
	    StringBuilder builder= new StringBuilder();
	    String value;
	    
	    int num =100;
	    for(String totalCode:menuCodeList){
	    	//String checkTotalCode = String.format("%s%03d", totalCode,num++);		    
	    	num =getTotalCodeNum(totalCode);
		    for(int i=0;i<menuLinkList.size();i++){
		    	value = menuLinkList.get(i);
		    	//检查链接是否存在
		    	if(!isExistMenuLink(totalCode,value)){
		    	value = fixMenuLink(value);
		    	//拼接insert
		    	builder.append(String.format(insertSql,ISystemConstant.DICTIONARY_FUNCTION_PROPERTY_3, value,totalCode,num,value))
		    	       .append("\r\n")
		    	       .append(String.format(insertAuthResourceSql,value,totalCode,num,totalCode,num)).append("\r\n")
		    	       .append(String.format(updateSeqSeql,"RM_FUNCTION_NODE")).append("\r\n")
		    	       ;
		    	num++;
		    	}
		   	}
		}	    

		FileOperateHelper.writeStringToFile(new File(sqlFile), builder.toString(), ISystemConstant.ENCODE_UTF_8);
	}
	/**
	 * 修理菜单链接
	 * @param value
	 * @return
	 */
	public String fixMenuLink(String value) {
		//去掉$
		value = StringHelper.replaceAll(value, "$", "").toString();
		//如果以=结束，后面加上{id}
		if(value.endsWith("=")){
			value=value+"{id}";
		}
		return value;
	}
	/**
	 * 判断在同级菜单下是否存在
	 * @param totalCode
	 * @param value
	 * @return
	 */
	public boolean isExistMenuLink(String totalCode, String value) {
		String sql="select count(*) from rm_function_node where total_Code like '"+totalCode+"%' and data_value='"+value+"' and FUNCTION_PROPERTY='"+ISystemConstant.DICTIONARY_FUNCTION_PROPERTY_3+"'";
		if(RmProjectHelper.getCommonServiceInstance().doQueryForInt(sql)>0){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 初始化菜单
	 */
	private void initMenuList() {
		String sql="select total_code,data_value from rm_function_node";
		
		List<RmCommonVo> vos = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
		exitsMenuMap = new HashMap<String,String>();
		for(RmCommonVo vo:vos){
			exitsMenuMap.put(vo.getString("total_code"), vo.getString("data_value"));
		}
	}
	/**
	 * 提取每个文件链接
	 * @param fileName
	 * @param menuCodeList 
	 * @return 
	 * @return
	 * @throws Exception 
	 */
	public ArrayList<String> pickLinkFromFile(String fileName, List<String> menuCodeList) throws Exception {
		File file = new File(fileName);
		String jspContent = FileOperateHelper.readFileToString(file,ISystemConstant.ENCODE_UTF_8);        
		
	    Matcher m = firstwp.matcher(jspContent);
	    
	    
	    String menulink="";
	    while(m.find()){
	    	for(int i=1;i<=m.groupCount();i++){
	    		menulink=m.group(i);
	    		if(!StringHelper.isEmpty(menulink)&&StringHelper.findStrNum(menulink, "/")>0 && StringHelper.findStrNum(menulink, "<")==0 && StringHelper.findStrNum(menulink, ">")==0){
	    			System.out.println(menulink);
	    			break;
	    		}
	    	}
			if(!menuLinkList.contains(menulink) && StringHelper.findStrNum(menulink, "/")>0 && StringHelper.findStrNum(menulink, "<")==0 && StringHelper.findStrNum(menulink, ">")==0){
				menuLinkList.add(menulink);
			}
    	}
	    return menuLinkList;		     
	}
	/**
	 * 获取TOTAL_CODE的页内链接
	 * @param totalCode
	 * @return
	 */
	private int getTotalCodeNum(String totalCode) {
		String checkTotalCode;
		int num=100;
		while(true){
			checkTotalCode = String.format("%s%03d", totalCode,num);
			if(!exitsMenuMap.containsKey(checkTotalCode)){
				return num;
			}
			num = num +1;
		}
	}
	public ArrayList<String> getMenuLinkList() {
		return menuLinkList;
	}
	public void setMenuLinkList(ArrayList<String> menuLinkList) {
		this.menuLinkList = menuLinkList;
	}
}
